
<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :labelWidth="105" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      selectionType="single"
      :isSelectColumn="false"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'records'"
      columnsRef="ownerQuerylswvm"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    >
      <template slot="controls">
        <AjaxButton size="small" type="primary" icon="el-icon-download" :click="ownerExportData">下载</AjaxButton>
      </template>
    </FilterTable>
    <Drawer :visible.sync="visible" :title="'车主车辆信息明细'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DetailForm @close="close" @save="save" :rowData="vin"></DetailForm>
    </Drawer>
    <Drawer :visible.sync="editVisible" :title="'车主车辆信息编辑'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="editClose" @save="editSave" :rowData="vin"></EditForm>
    </Drawer>
    <!-- <BaseDialog :visible.sync="actions.visible" :title="actions.title" width="300" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchDearlerList :resData="this.resData" @dealerData="dealerData" @close="closeSetting('dealer')" />
    </BaseDialog> -->
    <!-- <Drawer :visible.sync="actionsOwner.visible" :title="actionsOwner.title" width="60%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ownerQueryPanel :formData="this.resData" @close="closeSetting('owner')" />
    </Drawer> -->
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import DetailForm from './DetailForm';
import EditForm from './EditForm';
import { isFormEmpty, notifyAction, findTableItem } from '@/utils';
import { exportExcelFile } from '@/utils/index';
import { getDealerLabourHourList, getAllSeries, getModelsBySeries } from '@/api/repair/repairBusiness/labourHour/index.js';
import { getPinpSelect, getChexSelect, getCheModelSelect } from '@/api/repair/repairReception/customer/brand.js';
//import { getDearlerListByTranslate } from '@/api/customerRepair/vehicleOwnerManagement/vehicleChange';
import {
  getProvince,
  getCitys,
  getDistrict,
  getRegion,
  exportMaintainList, getOwnerAndVehicleInfoNew
} from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { getOwnerAndVehicleInfo, exportOwnerAndVehicleInfo } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import searchDearlerList from '@/pages/customerRepair/vehicleOwnerManagement/vehicleChangeQuery/searchDearlerList';
import {
  getListService,
  exportRepair,
  exportRepairModel,
  updateStatesRepairItem,
  getCarSeries,
  getCarModels,
  sendDown,
  getModelList
} from '@/api/claim/dealer/AuthMaintenance';
// import ownerQueryPanel from './ownerQueryPanel';
import moment from 'moment';

export default {
  name: 'ownerAndVehicleMaintain',
  components: {
    searchDearlerList,
    DetailForm,
    EditForm
    // ownerQueryPanel
  },
  mixins: [dictionary],
  data() {
    this.selectedData = null;
    this.BaseTable = null;
    this.resData = null;
    this.allSeries = {};
    return {
      visible: false,
      editVisible: false,
      vin: null,
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchapi: getOwnerAndVehicleInfoNew,
      fetchParams: { type: 'OEM', xhrAbort: true },
      actions: { visible: false, title: '', type: '' },
      actionsOwner: { visible: false, title: '', type: '' },
      dealerList: [] // 经销商列表
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table;
    // 查询经销商
    //this.getDearlerListByTranslate();
    // 获取省
    // this.getProvine();
    // 获取省市
    // this.getRegion();
    this.getAllSeries();
  },
  methods: {
    save() {
      this.visible = false;
    },
    close() {
      this.visible = false;
    },
    editSave() {
      this.editVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editClose() {
      this.editVisible = false;
    },
    chooseOrderNo(val) {
      console.log(val)
      this.vin = val.vin;
      console.log("vin",this.vin)
      this.visible = true;
    },
    chooseOrderNo2(val) {
      console.log(val)
      this.vin = val.vin;
      console.log("vin",this.vin)
      this.editVisible = true;
    },
    getCarSeriesData() {
      let dataArr = [];
      let tempArr = [];
      getCarSeries().then((res) => {
        if (res.resultCode === 200) {
          res.data.forEach((item) => {
            if (item.SERIES_CODE && !tempArr.includes(item.SERIES_CODE)) {
              tempArr.push(item.SERIES_CODE);
              dataArr.push({ text: item.SERIES_CODE, value: item.SERIES_CODE, id: item.SERIES_ID });
            }
          });
          this.seriesList = dataArr;
        }
      });
      return dataArr;
    },
    async getCarModelData(code, type, isTopFilter = false) {
      let series = this.seriesList.find(item => item.text === code);
      let dataArr = [];
      console.log(series)
      if (series && series.id) {
        await getModelList(null, series.id, null).then((res) => {
          console.log(res)
          if (res.resultCode === 200) {
            if (type == 'edit' && isTopFilter) {
              this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
              this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({ text: x.modelName, value: x.modelCode }));
            }
            res.data.forEach((item) => {
              dataArr.push({ text: item.MODEL_CODE1, value: item.MODEL_CODE1 })
            })
          }
          this.modelList = dataArr;
        });
      }
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '车主手机号',
          fieldName: 'mobile'
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesCode',
          placeholder: '请选择...',
          itemList: this.getCarSeriesData(),
          change: (val) => {
            console.log(val, this.topFilterList);
            if (val) {
              this.getCarModelData(val, 'edit', true);
            } else {
              this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = [];
              this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
            }
          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },
        {
          type: 'RANGE_DATE',
          label: '保修起始日期',
          fieldName: 'wrtBeginDateStart|wrtBeginDateEnd',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ]
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'RANGE_DATE',
          label: '销售日期',
          fieldName: 'salesDateStart|salesDateEnd',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ]
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          // sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo2(props.row)}>
                  编辑
                </multiuse-button>
                <el-divider direction="vertical"/>
                <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '车主姓名',
          dataIndex: 'ownerName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车主手机号',
          dataIndex: 'mobile',
          width: 120,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车主性质',
          dataIndex: 'ownerPropertyName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '品牌',
          width: 90,
          dataIndex: 'brandName',
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车系',
          width: 90,
          dataIndex: 'seriesName',
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '电机号',
          dataIndex: 'motorNo1',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '电池包编号',
          dataIndex: 'batteryNo',
          width: 230,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '销售经销商代码',
          dataIndex: 'salesDealerCode',
          width: 120,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '销售经销商简称',
          dataIndex: 'salesDealerName',
          width: 120,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '保修开始日期',
          dataIndex: 'wrtBeginDate',
          dateFormat: 'yyyy-MM-dd',
          width: 100,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '营运性质',
          dataIndex: 'businessKindName',
          width: 100,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '发动机号',
          dataIndex: 'engineNo',
          width: 120,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '变速器',
          dataIndex: 'gearBox',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '开票日期',
          dataIndex: 'invoiceDate',
          dateFormat: 'yyyy-MM-dd',
          width: 100,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '销售日期',
          dataIndex: 'salesDate',
          dateFormat: 'yyyy-MM-dd',
          width: 100,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 120,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '传真',
          dataIndex: 'fax',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '证件类型',
          dataIndex: 'ctCodeName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '证件号码',
          dataIndex: 'certificateNo',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '邮编',
          dataIndex: 'zipCode',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },

        {
          title: '省',
          dataIndex: 'provinceName',
          width: 90,
          dictItems: [],
          sorter:true,
          showOverflowTooltip: true,
        },
        {
          title: '市',
          dataIndex: 'cityName',
          width: 90,
          dictItems: [],
          sorter:true,
          showOverflowTooltip: true,
        },
        {
          title: '区/县',
          dataIndex: 'districtName',
          width: 90,
          dictItems: [],
          sorter:true,
          showOverflowTooltip: true,
        },
        {
          title: '地址',
          dataIndex: 'address',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '生日',
          dataIndex: 'birthday',
          dateFormat: 'yyyy-MM-dd',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: 'E_mail',
          dataIndex: 'email',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '性别',
          dataIndex: 'genderName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        }
      ];
    },
    changeHandle(val) {
      // 搜索和重置都走
      let params = { ...this.fetchParams, ...val, ...{ xhrAbort: false } };
      if (params.ownerShortName && params.ownerShortName.length) {
        params.ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue;
      } else {
        params.ownerCode = undefined;
      }
      // if (!val.ownerName && !val.license && !val.vin && !val.salesDateStart && !val.salesDateEnd) {
      //   return this.$notify.warning({ title: '提示信息', message: 'vin,车牌号,客户姓名,销售日期必填其一' });
      // }
      // if (val.salesDateStart || val.salesDateEnd) {
      //   let diffMonth = moment(val.salesDateEnd).diff(moment(val.salesDateStart), 'months');
      //   if (diffMonth > 11) return this.$notify.warning({ title: '提示信息', message: '销售起止日期跨度不能超过一年' });
      // }
      this.fetchParams = params;
    },
    async getAllSeries() {
      let res = await getChexSelect('null');
      if (res.resultCode === 200) {
        let series = res.data.map(x => {
          return { value: x.seriesCode, text: x.seriesName };
        });
        this.topFilterList.find(x => x.fieldName === 'seriesCode').itemList = series;
        this.allSeries = res.data;
      }
    },
    async getModelsBySeries(val) {
      let res = await getCheModelSelect('null', val);
      if (res.resultCode === 200) {
        let models = res.data.map(x => {
          return { value: x.modelCode, text: x.modelName };
        });
        this.topFilterList.find(x => x.fieldName === 'modelLabourCode').itemList = models;
      }
    },
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    },
    onRowSelectChange(row) {
      if (!row.length) {
        this.selectedData = null;
      } else {
        this.selectedData = row[0];
      }
    },
    // 获取经销商数据
    // dealerData(val) {
    //   this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue = val.dealerCode;
    //   this.topFilterList.find(x => x.fieldName === 'ownerShortName').initialValue = val.dealerShortname;
    //   this.closeSetting('dealer');
    // },
    // 关闭经销商页面
    closeSetting(type) {
      if (type === 'dealer') {
        this.actions.visible = false;
      } else if (type === 'owner') {
        this.actionsOwner.visible = false;
      }
    },
    // 查询全部经销商列表
    // async getDearlerListByTranslate() {
    //   const res = await getDearlerListByTranslate();
    //   console.log(JSON.stringify(res.data)+"+++++++++++++++++++++++++++++==res.data")
    //   if (res.resultCode === 200) {
    //     if (res.errMsg) {
    //       notifyAction(res.errMsg, 'error');
    //     } else {
    //       this.dealerList = res.data;
    //     }
    //   }
    // },
    // 翻译经销商列表
    // getText(val) {
    //   return this.dealerList.find(x => x.dealerCode === val) ? this.dealerList.find(x => x.dealerCode === val).dealerName : '';
    // },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    //获取省
    async getProvine() {
      const res = await getProvince();
      this.topFilterList.find(item => item.fieldName === 'province').itemList = res.data.map(x => ({ value: x.regionCode + '', text: x.regionName }));
    },
    // 获取市下拉框
    async provinceChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'city'));
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'distinct'));
      if (!regionId) return;
      const res = await getCitys(regionId);
      this.topFilterList.find(item => item.fieldName === 'city').itemList = res.data.map(x => ({ value: x.regionCode, text: x.regionName }));
    },
    // 获取区下拉框
    async cityChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'distinct'));
      if (!regionId) return;
      const res = await getDistrict(regionId);
      this.topFilterList.find(item => item.fieldName === 'distinct').itemList = res.data.map(x => ({ value: x.regionCode, text: x.regionName }));
    },
    // 获取省市
    async getRegion() {
      const allRegion = await getRegion();
      let regionList = allRegion.data.map(x => ({ value: x.regionCode + '', text: x.regionName }));
      let targetTableItems = [findTableItem(this.columns, 'province'), findTableItem(this.columns, 'city'), findTableItem(this.columns, 'district')];
      targetTableItems.forEach(item => {
        item.dictItems = regionList;
      });
    },
    // 车主导出
    async ownerExportData() {
      await exportMaintainList({params: this.fetchParams}).then(res => {
        console.log(res);
        exportExcelFile(res.data, '车主车辆信息维护导出');
      });
    }
  }
};
</script>
<style lang="less" scoped></style>
